<template>
  <div class="writeoff-container">
    <div class="controls-section">
      <div class="filters">
        <button class="btn-primary" @click="openCreate">新建</button>
        <div class="filter-item">
          <label>核销单号</label>
          <input v-model="query.writeOffNo" type="text" placeholder="输入核销单号">
        </div>
        <div class="filter-item">
          <label>收款单ID</label>
          <input v-model.number="query.receiptOrderId" type="number" placeholder="输入收款单ID">
        </div>
      </div>
      <div class="actions">
        <button class="btn-primary" @click="onSearch">搜索</button>
        <button class="btn-secondary" @click="onReset">重置</button>
      </div>
    </div>

    <div class="table-section">
      <table>
        <thead>
          <tr>
            <th>收款单号</th>
            <th>客户</th>
            <th>收款单ID</th>
            <th>核销金额</th>
            <th>核销日期</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="row in list" :key="row.id">
            <td class="link" @click="viewDetail(row)">{{ row.receiptOrderNo || '-' }}</td>
            <td>{{ row.customerName || row.customerId }}</td>
            <td>{{ row.receiptOrderId }}</td>
            <td>{{ money(row.amount) }}</td>
            <td>{{ date(row.writeOffDate) }}</td>
            <td><button class="btn-link" @click="viewDetail(row)">查看</button></td>
          </tr>
        </tbody>
      </table>
    </div>

    <div class="pagination-section">
      <div class="pagination-info">共 {{ total }} 条记录</div>
      <div class="pagination-controls">
        <button class="btn-pagination" :disabled="pageNum<=1" @click="changePage(pageNum-1)">‹</button>
        <button class="btn-pagination active" disabled>{{ pageNum }}</button>
        <button class="btn-pagination" :disabled="pageNum>=pages" @click="changePage(pageNum+1)">›</button>
        <select v-model.number="pageSize" @change="onChangeSize">
          <option :value="5">5条/页</option>
          <option :value="10">10条/页</option>
          <option :value="20">20条/页</option>
        </select>
      </div>
    </div>

    <!-- 详情抽屉 -->
    <div class="detail-drawer" v-if="showDetail">
      <div class="drawer-body">
        <div class="drawer-header">
          <span>收款核销详情</span>
          <button class="btn-secondary" @click="showDetail=false">关闭</button>
        </div>
        <div class="drawer-content">
          <div class="detail-grid">
            <div class="detail-item"><label>收款单号</label><span>{{ detail?.receiptOrderNo || '-' }}</span></div>
            <div class="detail-item"><label>客户</label><span>{{ detail?.customerName || detail?.customerId }}</span></div>
            <div class="detail-item"><label>收款单ID</label><span>{{ detail?.receiptOrderId }}</span></div>
            <div class="detail-item"><label>核销金额</label><span class="amount">{{ money(detail?.amount) }}</span></div>
            <div class="detail-item"><label>核销日期</label><span>{{ date(detail?.writeOffDate) }}</span></div>
            <div class="detail-item"><label>备注</label><span>{{ detail?.remark || '-' }}</span></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 新建弹窗 -->
    <div class="modal-overlay" v-if="showCreate" @click="closeCreate">
      <div class="create-modal" @click.stop>
        <div class="modal-header">
          <h3>新建收款核销</h3>
          <button class="close-btn" @click="closeCreate">×</button>
        </div>
        <div class="modal-content">
          <form @submit.prevent="submit">
            <div class="form-grid">
              <div class="form-group">
                <label>收款单号</label>
                <input v-model="form.receiptOrderNo" type="text" placeholder="自动生成，保存后显示" disabled>
              </div>
              <div class="form-group">
                <label class="required">客户ID</label>
                <input v-model="form.customerId" type="number" required placeholder="请输入客户ID">
              </div>
              <div class="form-group">
                <label class="required">收款单ID</label>
                <input v-model="form.receiptOrderId" type="number" required placeholder="请输入收款单ID">
              </div>
              <div class="form-group">
                <label class="required">核销金额</label>
                <input v-model="form.amount" type="number" step="0.01" required placeholder="请输入核销金额">
              </div>
              <div class="form-group">
                <label>核销日期</label>
                <input v-model="form.writeOffDate" type="date">
              </div>
              <div class="form-group">
                <label>备注</label>
                <input v-model="form.remark" type="text" placeholder="备注">
              </div>
            </div>
            <div class="form-actions">
              <button type="button" class="btn-secondary" @click="closeCreate">取消</button>
              <button type="submit" class="btn-primary" :disabled="saving">{{ saving ? '保存中...' : '保存' }}</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { writeOffPage, writeOffDetail, writeOffCreate } from '@/api/finance/receiptWriteOff'
export default {
  name: 'ReceiptWriteOff',
  data() {
    return {
      query: { writeOffNo: '', receiptOrderId: null },
      pageNum: 1,
      pageSize: 5,
      pages: 1,
      total: 0,
      list: [],
      showDetail: false,
      detail: null,
      showCreate: false,
      saving: false,
      form: { writeOffNo: '', customerId: null, receiptOrderId: null, amount: null, writeOffDate: '', remark: '' }
    }
  },
  mounted() { this.onSearch() },
  methods: {
    async onSearch() {
      const payload = { pageNum: this.pageNum, pageSize: this.pageSize, ...this.query }
      if (payload.writeOffNo === '') payload.writeOffNo = null
      const { data } = await writeOffPage(payload)
      const page = data?.data || data || {}
      this.list = page.records || []
      this.total = page.total || 0
      this.pages = Math.max(1, Math.ceil((this.total) / this.pageSize))
    },
    onReset() {
      this.pageNum = 1
      this.pageSize = 10
      this.query = { writeOffNo: '', receiptOrderId: null }
      this.onSearch()
    },
    changePage(p) {
      if (p < 1 || p > this.pages) return
      this.pageNum = p
      this.onSearch()
    },
    onChangeSize() {
      this.pageNum = 1
      this.onSearch()
    },
    openCreate() { this.showCreate = true },
    closeCreate() { this.showCreate = false },
    async viewDetail(row) {
      if (!row?.id) return
      const { data } = await writeOffDetail(row.id)
      this.detail = data?.data || data
      this.showDetail = true
    },
    formatDateTimeForBackend(v) {
      if (!v) return null
      // if it's already like 'yyyy-MM-dd HH:mm:ss'
      if (typeof v === 'string') {
        if (/^\d{4}-\d{2}-\d{2}$/.test(v)) return v + ' 00:00:00'
        if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/.test(v)) {
          // e.g. 2025-09-04T12:30 -> 2025-09-04 12:30:00
          const d = new Date(v)
          if (!isNaN(d.getTime())) return this.dt(d)
        }
        if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(v)) return v
      }
      const d = new Date(v)
      if (!isNaN(d.getTime())) return this.dt(d)
      return null
    },
    dt(d) {
      const pad = n => (n < 10 ? '0' + n : '' + n)
      return (
        d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()) +
        ' ' + pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds())
      )
    },
    async submit() {
      if (!this.form.customerId || !this.form.receiptOrderId || !this.form.amount) return alert('请填写必填项')
      this.saving = true
      try {
        const payload = {
          ...this.form,
          customerId: Number(this.form.customerId),
          receiptOrderId: Number(this.form.receiptOrderId),
          amount: Number(this.form.amount)
        }
        // 不提交空的收款单号字段
        if (!payload.writeOffNo) delete payload.writeOffNo
        // 空日期不传，避免后端日期解析错误
        if (payload.writeOffDate) {
          const normalized = this.formatDateTimeForBackend(payload.writeOffDate)
          if (normalized) payload.writeOffDate = normalized
          else delete payload.writeOffDate
        } else {
          delete payload.writeOffDate
        }
        // 删除所有空字符串字段
        Object.keys(payload).forEach(k => { if (payload[k] === '') delete payload[k] })
        const { data } = await writeOffCreate(payload)
        if (data?.code === 200) {
          alert('保存成功')
          this.closeCreate()
          this.onSearch()
        } else {
          alert(data?.msg || '保存失败')
        }
      } catch (e) {
        alert('保存失败')
      } finally {
        this.saving = false
      }
    },
    money(v) { if (v == null) return '-' ; const n = Number(v); return isNaN(n) ? '-' : n.toFixed(2) },
    date(ts) { if (!ts) return '-' ; const d = new Date(ts); return isNaN(d.getTime()) ? '-' : d.toISOString().slice(0,10) }
  }
}
</script>

<style scoped>
.writeoff-container { padding: 20px; background: #f5f7fa; }
.controls-section { display:flex; justify-content: space-between; align-items:center; padding:16px 20px; background:#fff; border-radius:8px; margin-bottom:16px; }
.filters { display:flex; align-items:center; gap:16px; }
.filter-item { display:flex; align-items:center; gap:8px; }
.filter-item input { padding:6px 10px; border:1px solid #dcdfe6; border-radius:4px; }
.actions { display:flex; gap:8px; }
.btn-primary { background:#409eff; color:#fff; border:none; border-radius:4px; padding:6px 12px; cursor:pointer; }
.btn-secondary { background:#fff; color:#333; border:1px solid #dcdfe6; border-radius:4px; padding:6px 12px; cursor:pointer; }
.btn-link { background:none; border:none; color:#409eff; cursor:pointer; }
.table-section { background:#fff; border-radius:8px; padding:16px; }
table { width:100%; border-collapse: collapse; }
th, td { padding:12px; border-bottom:1px solid #ebeef5; text-align:left; }
.link { color:#409eff; cursor:pointer; }
.pagination-section { display:flex; justify-content: space-between; align-items:center; background:#fff; border-radius:8px; padding:12px 16px; margin-top:16px; }
.pagination-controls { display:flex; align-items:center; gap:8px; }
.btn-pagination { width:32px; height:32px; display:flex; align-items:center; justify-content:center; border:1px solid #dcdfe6; border-radius:4px; background:#fff; }
.btn-pagination.active { background:#409eff; color:#fff; border-color:#409eff; }
.btn-pagination:disabled { color:#c0c4cc; border-color:#ebeef5; cursor:not-allowed; }
.pagination-controls select { padding:4px 8px; border:1px solid #dcdfe6; border-radius:4px; background:#fff; height:32px; }

.detail-drawer { position:fixed; inset:0; background:rgba(0,0,0,.45); z-index:1000; }
.drawer-body { position:absolute; right:0; top:0; height:100%; width:720px; background:#fff; box-shadow:-2px 0 12px rgba(0,0,0,.15); overflow:auto; }
.drawer-header { display:flex; justify-content:space-between; align-items:center; padding:16px 20px; background:#fafafa; border-bottom:1px solid #eee; }
.drawer-content { padding:20px; }
.detail-grid { display:grid; grid-template-columns:1fr 1fr; gap:12px 16px; }
.detail-item { display:flex; gap:8px; }
.detail-item label { min-width:100px; color:#666; }
.detail-item .amount { color:#409eff; font-weight:600; }

.modal-overlay { position:fixed; inset:0; background:rgba(0,0,0,.45); display:flex; align-items:center; justify-content:center; z-index:1001; }
.create-modal { width:760px; max-height:80vh; overflow:auto; background:#fff; border-radius:8px; }
.modal-header { padding:16px 20px; background:#8ec7ff; color:#fff; border-radius:8px 8px 0 0; display:flex; justify-content:space-between; align-items:center; }
.modal-content { padding:20px; }
.form-grid { display:grid; grid-template-columns:1fr 1fr; gap:16px 20px; }
.form-group { display:flex; flex-direction:column; gap:8px; }
.form-group input { height:36px; padding:0 10px; border:1px solid #dcdfe6; border-radius:4px; }
.form-group label.required::after { content:' *'; color:#f56c6c; }
.form-actions { display:flex; justify-content:flex-end; gap:12px; padding-top:16px; border-top:1px solid #eee; }
</style>
